import os
import xlrd
import json
from workspace.Platform.codegen import  codegen  # 绝对导入
from workspace.Project.InteractionProcess.interaction_dbc_json import Dbc_obj


protocol_file_path = ""

def get_ui_input_protocol_filePath():
    return protocol_file_path

def set_ui_input_protocol_filePath(filepath):
    global protocol_file_path
    protocol_file_path = filepath
    
def interaction_process():
    # Define  interaction module 的对象 object
    print("Interction module: Define interaction module object")
    interactionOBJ = InteractionModule("Interaction", "interaction_rules", "mcuInteractionToAdapter", "M83-001-020MM01 CAN DataBase for SC_CANFD_V6.3")
    interactionOBJ.loadProtocolAndConvert2Json()
    interactionOBJ.insertDbcInfo()
    interactionOBJ.codeFromJsonTemplates()
    print("Interction module: interaction_process end")
    
class InteractionModule:
    def __init__(self, module_name, rules_name, protocol_Name, dbc_name):
        self._module_name = module_name
        self._rules_name = rules_name
        self._protocol_name = protocol_Name
        self._dbc_name = dbc_name
        self._template_files = []
        self._protocol_file_path = get_ui_input_protocol_filePath()# os.path.join("project", "configure", self._module_name, self._protocol_name + '.xlsx')
        self._json_file_path = os.path.join("project", "configure", self._module_name, "rules",self._rules_name + '.json')
    # 根据json文件，以及template，生成interaction代码
    def codeFromJsonTemplates(self):
        # code_gen = CodeGenerator("./project/configure/Interaction/interaction.json")
        cg = codegen.CodeGenerator(self._module_name, self._rules_name)
        # 从配置文件中加载规则
        # rules = cg.load_rules("interaction_rules")
        rules = cg.load_rules("interaction_rules")
        cg.save_rules(rules)
        # 读取指定目录下的模板文件
        cg.read_template("src")
        # 使用Jinja2模板引擎将规则应用于模板文件，并生成输出文件    
        cg.generator(rules, "CAP_InteractionAppHandlerProcess_c.template", "CAP_InteractionAppHandlerProcess.c", "与其他模块进行协议交互的处理文件")
        cg.generator(rules, "CAP_InteractionIfal_c.template", "CAP_InteractionIfal.c", "信号操作接口的定义")
        cg.read_template("inc")
        cg.generator(rules, "CAP_InteractionIfal_h.template", "CAP_InteractionIfal.h", "信号操作接口的定义")
        cg.generator(rules, "Plm_IApp_Types_h.template", "Plm_IApp_Types.h", "数据结构")
    # 处理协议表格信息，生成json文件
    def loadProtocolAndConvert2Json(self):
        convert_excel2json(self._protocol_file_path, self._json_file_path)
        
    # 将dbc信息加入json
    def insertDbcInfo(self):
        dbcObj = Dbc_obj(self._json_file_path)
        dbcObj.AddInfo_matchJSON()


# 按照标准Excel格式将通讯协议内容转化为json文件
def convert_excel2json(protocol_path, json_path):
    # 读取 Excel 文件内容
    xlsx_file = xlrd.open_workbook(protocol_path)
    json_content = {}

    group_max_typeid = 0
    group_dict = {"groups": []}
    group_num = 0
    for sheet_name in xlsx_file.sheet_names():
        group_obj = {}
        sheet = xlsx_file.sheet_by_name(sheet_name)
        # print(f"---------------------------{sheet_name.title()}, this is a new sheet:")
        # print(f"sheet rows:{sheet.nrows}")
        # print(f"sheet cols:{sheet.ncols}")
        # 遍通过行列遍历表格中每个cell的内容
        for row in range(sheet.nrows):
            for col in range(sheet.ncols):
                cell_value = sheet.cell(row, col).value
                if isinstance(cell_value, str):
                    # 获取数据组开始标志
                    if "group description start:" in cell_value:
                        #print(f"group description start! start row: {row}")
                        group_obj["group_name"]     = sheet.cell(row + 1, 2).value
                        group_obj["struct_name"]   = sheet.cell(row + 2, 2).value
                        group_obj["group_comment"]  = sheet.cell(row + 3, 2).value
                        group_obj["group_typeID"]   = int(sheet.cell(row + 6, 5).value)
                        if group_obj["group_typeID"] > group_max_typeid and group_obj["group_typeID"] < 100:
                            group_max_typeid = group_obj["group_typeID"]
                        group_obj["signal_list"]    = [] # move initialization here

                        #group_start_row = row
                    # 获取信号描述的开始标志
                    if "data description start:" in cell_value:
                        #print(f"data description start! start row: {row}")
                        signal_data_process_ing = 1
                        signal_description_start_row = row
                        signal_end_row = 0
                    if "Interaction results" in cell_value:
                        signal_start_row = row + 1
                    # 检测当前表格是否为adapter下设的命令组数据，如果是命令组数据，屏蔽信号组处理
                    if "GROUP-TYPE-CMD" in cell_value:
                        signal_start_row = 0
                    # 检测当前表格是否为adapter下设id组数据，如果是id组数据，屏蔽信号组处理
                    if "GROUP-TYPE-ID-DATA" in cell_value:
                        signal_start_row = 0
                    # 获取信号描述结束的标志
                    if "data description end" in cell_value:
                        #print(f"data description end! end row: {row}")
                        signal_data_process_ing = 0
                        signal_end_row = row
                    # 获取index所在列
                    if "index:" in cell_value:
                        index_col              = col
                    if "data type:" in cell_value:                        
                        dat_type_col           = col
                    if "data len:" in cell_value:
                        signal_data_len_col    = col
                    if "data name:" in cell_value:
                        signal_data_name_col   = col
                    if "factory value:" in cell_value:
                        factory_value_col      = col
                    if "sending condition:" in cell_value:
                        sending_condition_col  = col
                    if "data comment:" in cell_value:
                        signal_data_comment_col = col
                    if "group description end" in cell_value:
                        signalNum = 0
                        # print(f"group description end! end row: {row}")                        
                        while signal_start_row < signal_end_row and signal_start_row != 0:
                            # print(f"signal_start_row{signal_start_row}")
                            # print(f"signal_end_row{signal_end_row}")
                            signal_obj = {}
                            if index_col > 0 and signal_data_process_ing == 0:
                                signal_obj["signal_index"] = sheet.cell(signal_start_row, index_col).value
                                signal_obj["signal_data_type"] = sheet.cell(signal_start_row, dat_type_col).value
                                signal_obj["signal_data_len"] = int(sheet.cell(signal_start_row, signal_data_len_col).value)
                                signal_obj["signal_name"] = sheet.cell(signal_start_row, signal_data_name_col).value
                                signal_obj["factory_value"] = sheet.cell(signal_start_row, factory_value_col).value
                                signal_obj["send_condition"] = sheet.cell(signal_start_row, sending_condition_col).value
                                signal_obj["comment"] = sheet.cell(signal_start_row, signal_data_comment_col).value
                                signal_obj["message_name"] = ""
                                signal_obj["message_id"] = 0
                                signal_obj['message_id_hex'] = None
                                group_obj["signal_list"].append(signal_obj)
                                signalNum = signalNum + 1
                                # print(signal_obj)                                        

                            signal_start_row = signal_start_row + 1
                        group_obj['singnal_num'] = signalNum
                        signalNum = 0
                        group_dict["groups"].append(group_obj)
                        group_num = group_num +1
                        group_dict['groupNum'] = group_num
                        group_dict["typeIdMax"] = group_max_typeid
                        json_content["rules"] = group_dict
                        # don't delete group_obj here
                        # group_start_row     =  0
                        signal_start_row    =  0
                        signal_end_row      =  0
                        signal_description_start_row = 0
                        signal_data_process_ing =  0
                        index_col                  =  0
                        dat_type_col               =  0  
                        signal_data_len_col        =  0 
                        factory_value_col          =  0 
                        sending_condition_col      =  0 
                        signal_data_name_col       =  0 

    # print(json_content)
    with open(json_path, 'w') as f:
        json.dump(json_content, f)

